package org.example.algorithm.LinkList;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

public class MidLRUCache implements ILRUCache{

    private int capacity;

    private Map<Integer, Integer> map;

    MidLRUCache(int capacity){
        this.capacity = capacity;
        map = new LinkedHashMap<>();
    }

    @Override
    public int get(int key) {
        Integer value = map.get(key);
        if(Objects.nonNull(value)){
            if(map.size() > 1){
                map.remove(key);
                map.put(key,value);
            }
        }else{
            return -1;
        }
        return value;
    }

    @Override
    public void put(int key, int value) {
        if(map.containsKey(key)){
            map.remove(key);
        }else if(map.size() >= capacity){
            Integer integer = map.keySet().iterator().next();
            map.remove(integer);
        }
        map.put(key, value);
    }
}
